/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  themes_default
 */

var crop;
var image;
var mask;

var winHeight;
var winWidth;
var origWidth;
var origHeight;
var imgWidth;
var imgHeight;
var cropWidth;
var cropHeight;
var definedWidth;
var definedHeight;

var bgColor;
var ratio;
var origZoom;

$(document).ready(function() {
    image = $("#image");
    crop = $("#crop");

    $(image).ready(function() {
        $(image).show();
        
        $(image).clone().attr('id','imgMask').appendTo('.mask');
        mask = $('#imgMask');

        $('#loader').hide();

        origWidth = $(image).width();
        origHeight = $(image).height();
        ratio = origWidth/origHeight;
        origZoom = 100;

        imgWidth = origWidth;
        imgHeight = origHeight;
        definedWidth = $("#containerWidth").val();
        definedHeight = $("#containerHeight").val();

        init();
        enableColorPicker();
        enableZoomBar();        
        enableCrop();
        enableDrag(image);
        enableDrag(mask);
        enableFraming();

        $(window).bind('resize', function() {
            init();
        });
        
        catchSaveButtonClick();
        catchExitClick();
    });
});

function enableColorPicker()
{
    bgColor = '000000';
    $('.mask').css('backgroundColor', '#' + bgColor);

	$('#colorSelector').ColorPicker({
		color: '000000',
		onShow: function (colpkr) {
			$(colpkr).fadeIn(500);
			return false;
		},
		onHide: function (colpkr) {
			$(colpkr).fadeOut(500);
			return false;
		},
		onChange: function (hsb, hex, rgb) {
			$('#colorSelector div').css('backgroundColor', '#' + hex);
            $('.mask').css('backgroundColor', '#' + hex);
            bgColor = hex;
		}
	});
}

function enableZoomBar()
{
    var zoom = origZoom;
    
    var $slider = $('#slider');
    $slider.slider({
        min: 1,
        max: 400,
        orientation: "vertical",
        value: origZoom,
        start: function(e, ui) {

        },
        slide: function(e, ui) {
            zoom = ui.value;

            if(!$.browser.mozilla)
            {
                resize(ui.value);
            }
            else
            {
                resize(ui.value, false, true);
            }
        },
        stop: function (e, ui) {
            if($.browser.mozilla)
            {
                resize(ui.value);
            }
        }
    });

    $("#resetImage").click(function(){
        resize(100, true);
    });

    $("#zoomBig").mousedown(function(){
        if(zoom < $slider.slider('option', 'max'))
        {
            zoom = $slider.slider('value') + 1
            resize(zoom);
        }
    });

    $("#zoomSmall").mousedown(function(){
        if(zoom > $slider.slider('option', 'min'))
        {
            zoom = $slider.slider('value') - 1
            resize(zoom);
        }
    });

    $("#zoomSlider").keyup(function(){
        var val = $(this).val();

        if(val <= $slider.slider('option', 'max') && val >= $slider.slider('option', 'min'))
        {
            zoom = val;
            resize(zoom);
        }
    });
}

function enableDrag(obj)
{
	var origPosX = null;
	var origPosY = null;
	var imgX = null;
	var imgY = null;

	$(document).mousemove(function(e){
		if(origPosX > 0 && origPosY > 0)
		{
			var destX = parseInt(imgX) + (e.pageX - origPosX);
			var destY = parseInt(imgY) + (e.pageY - origPosY);

            if(e.pageX > 0 && e.pageY > 50 && e.pageX < $(window).width() && e.pageY < $(window).height() - 50)
            {
                $(obj).css({left: destX+"px",top: destY+"px"});
                $(obj).attr('id') == "imgMask" ? posMask(true) : posMask();
            }
		}

        return false;
	}).mouseup(function(e){
		origPosX = null;
		origPosY = null;
	});

	$(obj).mousedown(function(e){
		e.preventDefault();
		origPosX = e.pageX;
		origPosY = e.pageY;
		imgX = px($(obj).css("left"));
		imgY = px($(obj).css("top"));
	});
}

function enableCrop()
{
    cropInputResize();
    insertHandle();

    if(definedWidth == "" || definedHeight == "")
    {
        definedWidth = imgWidth;
        definedHeight = imgHeight;
    }

    cropResize(definedWidth, definedHeight);
    
    if($.browser.mozilla)
    {
        cropInfo();
    }
}

function enableFraming()
{
    var defaultCropSize;

    $("#cadre1").click(function(){
        defaultCropSize = getIeCropSize();
        resizePx(null, defaultCropSize["height"], true);
    });

    $("#cadre2").click(function(){
        resizePx(cropWidth, null, true);
    });

    $("#cadre3").click(function(){
        var cropRation = cropWidth/cropHeight;
        if(cropRation > ratio)
        {
            resizePx(null, $(crop).height(), true);
        }
        else
        {
            resizePx(cropWidth, null, true);
        }
    });
}

function cropInputResize()
{
    $("#containerWidth").keyup(function(){
        cropResize($(this).val(), null);
    });

    $("#containerHeight").keyup(function(){
        cropResize(null,$(this).val());
    });

    $("#formatSizes").change(function(){
        var dimTab = $(this).val().split("x");
        if(dimTab[0] != "")
        {
            cropResize(dimTab[0],dimTab[1]);

            if($.browser.mozilla)
            {
                cropInfo();
            }
        }
    });
}

function cropMouseResize(obj)
{
	var origPosX = null;
	var origPosY = null;
    var cropX = null;
    var cropY = null;
    var id = $(obj).attr('id');

	$(document).mousemove(function(e){
        if(origPosX > 0 && origPosY > 0)
        {
            var sizeX;
            var sizeY;
            var mouseDiffX = (e.pageX - origPosX)*2;
            var mouseDiffY = (e.pageY - origPosY)*2;

            switch (id)
            {
                case "nw":
                    sizeX = cropX - mouseDiffX;
                    sizeY = cropY - mouseDiffY;
                    cropResize(sizeX,sizeY);
                break;
                case "n":
                    sizeY = cropY - mouseDiffY;
                    cropResize(null,sizeY);
                break;
                case "ne":
                    sizeX = cropX + mouseDiffX;
                    sizeY = cropY - mouseDiffY;
                    cropResize(sizeX,sizeY);
                break;
                case "e":
                    sizeX = cropX + mouseDiffX;
                    cropResize(sizeX,null);
                break;
                case "se":
                    sizeX = cropX + mouseDiffX;
                    sizeY = cropY + mouseDiffY;
                    cropResize(sizeX,sizeY);
                break;
                case "s":
                    sizeY = cropY + mouseDiffY;
                    cropResize(null,sizeY);
                break;
                case "sw":
                    sizeX = cropX - mouseDiffX;
                    sizeY = cropY + mouseDiffY;
                    cropResize(sizeX,sizeY);
                break;
                case "w":
                    sizeX = cropX - mouseDiffX;
                    cropResize(sizeX,null);
                break;
            }
        }

        return false;
    }).mouseup(function(e){
		origPosX = null;
		origPosY = null;

        $("#page").css('cursor', 'default');

        if($.browser.mozilla)
        {
            cropInfo();
        }
    });

	$(obj).mousedown(function(e){
		e.preventDefault();
		origPosX = e.pageX;
		origPosY = e.pageY;
        cropX = cropWidth;
        cropY = cropHeight;
        $("#page").css('cursor', $(this).css('cursor'));
	});
}

function insertHandle()
{
    var handleTab = ["nw", "n", "ne", "e", "se", "s", "sw", "w"];
    
    $handle = $("<div />").addClass('handle');

    var cropWidth = imgWidth;
    var cropHeight = imgHeight;

    for (handle in handleTab)
    {
        obj = $handle.clone().attr("id", handleTab[handle]).css("cursor", handleTab[handle]+"-resize").appendTo(crop);
        cropMouseResize(obj);
    }
    
    posHandler();
}

function posHandler()
{
    hhs = 4;
    
    $("#nw").css({position: 'absolute', top: -hhs, left: -hhs});
    $("#n").css({position: 'absolute', top: -hhs, left: -hhs+cropWidth/2});
    $("#ne").css({position: 'absolute', top: -hhs, right: -hhs});
    $("#e").css({position: 'absolute', top: -hhs+ cropHeight/2, right: -hhs});
    $("#se").css({position: 'absolute', bottom: -hhs, right: -hhs});
    $("#s").css({position: 'absolute', bottom: -hhs, left: -hhs+cropWidth/2});
    $("#sw").css({position: 'absolute', left: -hhs, bottom: -hhs});
    $("#w").css({position: 'absolute', top: -hhs+ cropHeight/2, left: -hhs});
}

function cropResize(width, height)
{
    cropWidth = width != null ? parseInt(width) : $(crop).width();
    cropHeight = height != null ? parseInt(height) : $(crop).height();

    if(cropWidth >= 0 && cropHeight >= 0)
    {
        var ieSize = getIeCropSize();
        
        $(crop).width(ieSize['width']).height(ieSize['height']);
        if(!$.browser.mozilla)
        {
            cropInfo();
        }

        $(crop).css({top: winHeight/2-cropHeight/2-1, left: winWidth/2-cropWidth/2-1});
        posHandler();
        posMask();
    }
}

function init()
{
    var marge = 200;
    
    winHeight = $(window).height();
    winWidth = $(window).width();

	if(origWidth >= origHeight && $(image).width() > winWidth-marge)
	{
		$(image).width(winWidth-marge);
		origZoom = Math.round(($(image).width()/origWidth)*100);
	}

	if($(image).height() > winHeight-marge)
	{
		$(image).height(winHeight-marge);
		origZoom = Math.round(($(image).height()/origHeight)*100);
	}

    resize(origZoom, true);
    cropResize();
}

function resize(value, center, ff)
{
    imgPercentage = value/100;
    resizePx(Math.round(origWidth*imgPercentage), Math.round(origHeight*imgPercentage), center, ff);
}

function resizePx(width, height, center, ff)
{
    /* USEFUL TO CENTER THE REZISE */
    var curHeight = imgHeight;
    var curWidth = imgWidth;

    if(width)
    {
        imgWidth = width;
        if(!height)
        {
            imgHeight = Math.round(width/ratio);
        }
    }

    if(height)
    {
        imgHeight = height;
        if(!width)
        {
            imgWidth = Math.round(imgHeight*ratio);
        }
    }

    $(image).width(imgWidth).height(imgHeight);
    $(mask).width(imgWidth).height(imgHeight);

    var value = Math.round(imgHeight/origHeight*100);
    $('#slider').slider('value', value);
    if(ff != true)
    {
        $("#zoomSlider").val(value);
    }
    
    centerObj(image, center, curWidth, curHeight);

    posMask();
    info();
}

function posMask(reverse)
{
    var obj;
    
    if(reverse == true)
    {
        imgTop = px($(crop).css("top"))+px($(mask).css("top"))+1;
        imgLeft = px($(crop).css("left"))+px($(mask).css("left"))+1;
        obj = $(image);
    }
    else
    {
        imgTop = px($(image).css("top"))-px($(crop).css("top"))-1;
        imgLeft = px($(image).css("left"))-px($(crop).css("left"))-1;
        obj = $(mask);
    }

    $(obj).css({top: imgTop+"px", left: imgLeft+"px"});
    info();
}

function px(value)
{
    value = value.replace(/px/, "");
    value = parseInt(value);
    value = (isNaN(value)) ? 0 : value;
    return value;
}

function centerObj(obj, center, oldWidth, oldHeight)
{
    var topObj = px($(obj).css('top'));
    var leftObj = px($(obj).css('left'));

    var objWidth = $(obj).width();
    var objHeight = $(obj).height();

    var top = center ? winHeight/2-objHeight/2 : topObj+(Math.round(oldHeight/2))-Math.round(objHeight/2);
    var left = center ? winWidth/2-objWidth/2 : leftObj+(Math.round(oldWidth/2))-Math.round(objWidth/2);

    $(obj).css({top: top+"px", left: left+"px"});
}

//border
function getIeCropSize()
{
    var tab = Array();

    tab['width'] = $.browser.msie ? cropWidth + 2: cropWidth;
    tab['height'] = $.browser.msie ? cropHeight + 2 : cropHeight;

    return tab;
}

function catchExitClick()
{
    $("#exitButton").click(function(){
        closeWindow();
    });
}

function infoMessage(message)
{
	$('div#message').html(message).css('margin-left', '-'+($("div#message").width()/2)+"px").slideDown("normal", function(){
        $("div#message").delay(2500).slideUp('normal');
	});
}

function info()
{
    $("#currentSize").text(imgWidth + " x " + imgHeight);
    $("#posX").text(px($(mask).css("left")));
    $("#posY").text(px($(mask).css("top")));
}

function cropInfo()
{
    $("#containerWidth").val(cropWidth);
    $("#containerHeight").val(cropHeight);
}

function catchSaveButtonClick()
{
    $("#saveButton").click(function(){
        var text = $.ajax({
            type: "POST",
            url: "?module=medias&action=ResizePicture",
            data: ({
                docId:	$("#docId").val(),
                docLang:$("#docLang").val(),
                bgColor: bgColor,
                cropW:	cropWidth,
                cropH:	cropHeight,
                picW:   imgWidth,
                picH:   imgHeight,
                offsetX: px($(mask).css('left')),
                offsetY: px($(mask).css('top'))
            }),
            async: false
        }).responseText;
        
        if(text == "50")
        {
            if(confirm(getLocale('medias.locales.pictureExist')))
            {
                text = $.ajax({
                    type: "POST",
                    url: "?module=medias&action=ResizePicture",
                    data: ({
                        docId:	$("#docId").val(),
                        docLang:$("#docLang").val(),
                        bgColor: bgColor,
                        cropW:	cropWidth,
                        cropH:	cropHeight,
                        picW:   imgWidth,
                        picH:   imgHeight,
                        offsetX: px($(mask).css('left')),
                        offsetY: px($(mask).css('top')),
                        force: 1
                    }),
                    async: false
                }).responseText;
            }
        }

        if(text == "1")
        {
            infoMessage(getLocale('medias.locales.savePicture'));
            closeWindow();
        }
    });
}

function getLocale(key, params ,lang)
{
    var result;

    $.ajax({
            url: '?module=backoffice&action=AjaxGetLocale',
            data: {key:key, lang:lang, params:params},
            async: false,
            success: function(res)
            {
                result = res;
            }
    });

    return result;
}

function closeWindow()
{
    if(myOpener == 'editmedia') {
        window.opener.refreshFormats();
    }
    else if(myOpener == 'filemanager') {
        window.opener.loadMediaDetails($('#docId').val(), $('#docLang').val());
    }else if(myOpener == 'pictureselect')
    {
        window.opener.saveImg($('#docId').val());
    }
    window.close();
}